package com.liang.blog.security.shiro;

import com.liang.blog.Enum.user.UserStatusEnum;
import com.liang.blog.client.menu.MenuFeignClient;
import com.liang.blog.client.user.UserFeignClient;
import com.liang.blog.common.exception.BlogException;
import com.liang.blog.common.result.Result;
import com.liang.blog.common.result.ResultCodeEnum;
import com.liang.blog.model.BlogUser;
import com.liang.blog.security.jwt.JwtHelper;
import com.liang.blog.vo.menu.MenuPermissionVo;
import com.liang.blog.vo.user.LoginUserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * @Author：YanWenLiang
 * @Date:2023-08-17-17:17
 */

public class BlogRealm extends AuthorizingRealm {

    @Autowired
    private UserFeignClient userFeignClient;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection
                                                               principalCollection) {
            return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo
            (AuthenticationToken authenticationToken) throws AuthenticationException {
        // 根据身份信息
        String account = (String) authenticationToken.getPrincipal();
        Result<LoginUserVo> result = userFeignClient.getLoginUserInfo(account);

        // 获取当前登入用户信息
        LoginUserVo loginUserVo = result.getData();

        // 获取用户信息
        BlogUser blogUser = loginUserVo.getBlogUser();

        if (blogUser != null) {
            SecurityUtils.getSubject().getSession().setAttribute("user", loginUserVo);
            return new SimpleAuthenticationInfo(blogUser.getAccount(), blogUser.getPassword(),
                    ByteSource.Util.bytes(
                            new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss").format(blogUser.getCreateTime())),
                    this.getName());
        }
        return null;
    }

    @Override
    public void setName(String name) {
        super.setName("BlogRealm");
    }


}
